package com.wrial.simple;
/*
 * @Author  Wrial
 * @Date Created in 12:45 2020/3/26
 * @Description  合并两个有序链表
 */

public class LeetCode_21 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode head ;
        if (l1.val < l2.val) {
            head = l1;
            l1 = l1.next;
        } else {
            head = l2;
            l2 = l2.next;
        }
        ListNode temp = head;

        while (l1 != null && l2 != null) {
            if (l1.val<l2.val){
                temp.next = l1;
                l1 = l1.next;
            }else {
                temp.next = l2;
                l2 = l2.next;
            }
            temp = temp.next;
        }
        if (l1!=null){
            temp.next = l1;
        }
        if (l2!=null){
            temp.next = l2;
        }
        return head;

    }



    public void print(ListNode listNode) {
        while (listNode != null) {
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }
    }

    public static void main(String[] args) {
        LeetCode_21 leetCode_21 = new LeetCode_21();
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);
        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);
        ListNode listNode = leetCode_21.mergeTwoLists(l1, l2);
        leetCode_21.print(listNode);

    }

}
